package com.jaj.common;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

	public static void main(String[] args) throws Exception {

//		try {
//			String urlHttp = "http://localhost/trade/queryAmount";
//			String urlHttps = "https://localhost/trade/queryAmount";
//			String certPath = "D://certs/server.p12";// 证书
//			String password = "123456";// 证书密码
//			//String result = HttpUtils.httpsClientGet(urlHttp, certPath,"123456");
//			//String result = HttpUtils.httpsClientPost(urlHttp, "", certPath, password);
//			//String result = HttpUtils.httpsClientGetNoCerts(urlHttps);
//			//String result = HttpUtils.httpsClientPostNoCerts(urlHttps,"");
//			//System.out.println(result);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

	}

    /**
     *get请求
     * @param url url
     * @return
     * @throws Exception
     */
    public static String httpClientGet(String url,List<Header> headerList) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            if(headerList!=null&&headerList.size()>0){
                Header[] headers = new Header[headerList.size()];
                int i=0;
                for (Header header : headerList) {
                    headers[i]=header;
                    i++;
                }
                httpGet.setHeaders(headers);
            }
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
                HttpEntity entity1 = response1.getEntity();
                result = EntityUtils.toString(entity1, "UTF-8");
                EntityUtils.consume(entity1);
            } finally {
                response1.close();
            }
        } finally {
            httpclient.close();
        }
        return result;
    }


    /**
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static String  httpClientPostReturnCookie(String url,Map<String, String> map) throws Exception{
		CookieStore cookieStore = new BasicCookieStore();
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		HttpPost httpPost = new HttpPost(url);
		try {
			if(map!=null){
				List<NameValuePair> list = new ArrayList<>();
				Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry<String, String> elem = iterator.next();
					list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
				}
				if (list.size() > 0) {
					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
					httpPost.setEntity(entity);
				}
			}
			httpClient.execute(httpPost);
			List<Cookie> cookies = cookieStore.getCookies();
			for (int i = 0; i < cookies.size(); i++) {
				if (cookies.get(i).getName().equals("JSESSIONID")) {
					return cookies.get(i).getValue();
				}
			}
			return  null;
		} catch (Exception ex) {
			ex.printStackTrace();
			return  null;
		}
		finally {
			httpClient.close();
		}

	}


	/**
	 * @param url
	 * @param param
	 * @param headerList
	 * @return
	 * @throws Exception
	 */
	public static String httpClientPost(String url, Map<String,String> param, List<Header> headerList) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String result;
		try {
			HttpPost httpPost = new HttpPost(url);
			UrlEncodedFormEntity entity;
			List<NameValuePair> list = new ArrayList<>();
			for (Map.Entry<String,String> entry:param.entrySet()) {
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			entity=new UrlEncodedFormEntity(list,"utf-8");
			httpPost.setEntity(entity);			
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
					.build();// 设置请求和传输超时时间
			httpPost.setConfig(requestConfig);
			if(headerList!=null&&headerList.size()>0){
				Header[] headers = new Header[headerList.size()];
				int i=0;
				for (Header header : headerList) {
					headers[i]=header;
					i++;
				}
				httpPost.setHeaders(headers);
			}
			CloseableHttpResponse response2 = httpclient.execute(httpPost);

			try {
				HttpEntity entity2 = response2.getEntity();
				result = EntityUtils.toString(entity2, "UTF-8");
				EntityUtils.consume(entity2);
			} finally {
				response2.close();
			}
		} finally {
			httpclient.close();
		}
		return result;
	}



}
